Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import {PeerStats} from "./peer_stats.js"
import {WebSocketAdaptor} from "./websocket_adaptor.js"
import {MediaManager} from "./media_manager.js"
import {SoundMeter} from "./soundmeter.js"
import "./external/loglevel.min.js";
const Logger = window.log;
/**
* This structure is used to handle large size data channel messages (like image)
* which should be splitted into chunks while sending and receiving.
*
*/
class ReceivingMessage {
/**
*
* @param {number} size
*/
constructor(size) {
this.size = size;
this.received = 0;
this.data = new ArrayBuffer(size);
}
}
/**
* WebRTCAdaptor Class is interface to the JS SDK of Ant Media Server (AMS). This class manages the signalling,
* keeps the states of peers.
*
* This class is used for peer-to-peer signalling,
* publisher and player signalling and conference.
*
* Also it is responsible for some room management in conference case.
*
* There are different use cases in AMS. This class is used for all of them.
*
* WebRTC Publish
* WebRTC Play
* WebRTC Data Channel Connection
* WebRTC Conference
* WebRTC Multitrack Play
* WebRTC Multitrack Conference
* WebRTC peer-to-peer session
*
*/
export class WebRTCAdaptor {
/**
* @type {Array<Function>}
*/
static pluginInitMethods = new Array();
/**
* Register plugins to the WebRTCAdaptor
* @param {Function} plugin
*/
static register(pluginInitMethod) {
WebRTCAdaptor.pluginInitMethods.push(pluginInitMethod);
}
/**
*
* @param {object} initialValues
*/
constructor(initialValues) {
/**
* PeerConnection configuration while initializing the PeerConnection.
* https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection#parameters
*
* More than one STURN and/or TURN servers can be added. Here is a typical turn server configuration
*
* {
* urls: "",
* username: "",
* credential: "",
* }
*
* Default value is the google stun server
*/
this.peerconnection_config = {
'iceServers': [{
'urls': 'stun:stun1.l.google.com:19302'
}],
sdpSemantics: 'unified-plan'
};
/**
* Used while creating SDP (answer or offer)
* https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createOffer#parameters
*/
this.sdp_constraints = {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
};
;
/**
* This keeps the PeerConnections for each stream id.
* It is an array because one @WebRTCAdaptor instance can manage multiple WebRTC connections as in the conference.
* Its indices are the Stream Ids of each stream
*/
this.remotePeerConnection = new Array();
/**
* This keeps statistics for the each PeerConnection.
* It is an array because one @WebRTCAdaptor instance can manage multiple WebRTC connections as in the conference.
* Its indices are the Stream Ids of each stream
*/
this.remotePeerConnectionStats = new Array();
/**
* This keeps the Remote Description (SDP) set status for each PeerConnection.
* We need to keep this status because sometimes ice candidates from the remote peer
* may come before the Remote Description (SDP). So we need to store those ice candidates
* in @iceCandidateList field until we get and set the Remote Description.
* Otherwise setting ice candidates before Remote description may cause problem.
*/
this.remoteDescriptionSet = new Array();
/**
* This keeps the Ice Candidates which are received before the Remote Description (SDP) received.
* For details please check @remoteDescriptionSet field.
*/
this.iceCandidateList = new Array();
/**
* This is the name for the room that is desired to join in conference mode.
*/
this.roomName = null;
/**
* This keeps StreamIds for the each playing session.
* It is an array because one @WebRTCAdaptor instance can manage multiple playing sessions.
*/
this.playStreamId = new Array();
/**
* This is the flag indicates if multiple peers will join a peer in the peer to peer mode.
* This is used only with Embedded SDk
*/
this.isMultiPeer = false;
/**
* This is the stream id that multiple peers can join a peer in the peer to peer mode.
* This is used only with Embedded SDk
*/
this.multiPeerStreamId = null;
/**
* This is instance of @WebSocketAdaptor and manages to websocket connection.
* All signalling messages are sent to/recived from
* the Ant Media Server over this web socket connection
*/
this.webSocketAdaptor = null;
/**
* This flags indicates if this @WebRTCAdaptor instance is used only for playing session(s)
* You don't need camera/mic access in play mode
*/
this.isPlayMode = false;
/**
* This flags enables/disables debug logging
*/
this.debug = false;
/**
* This is the Stream Id for the publisher. One @WebRCTCAdaptor supports only one publishing
* session for now (23.02.2022).
* In conference mode you can join a room with null stream id. In that case
* Ant Media Server generates a stream id and provides it JoinedTheRoom callback and it is set to this field.
*/
this.publishStreamId = null;
/**
* This is used to keep stream id and track id (which is provided in SDP) mapping
* in MultiTrack Playback and conference.
*/
this.idMapping = new Array();
/**
* This is used when only data is brodcasted with the same way video and/or audio.
* The difference is that no video or audio is sent when this field is true
*/
this.onlyDataChannel = false;
/**
* While publishing and playing streams data channel is enabled by default
*/
this.dataChannelEnabled = true;
/**
* This is array of @ReceivingMessage
* When you receive multiple large size messages @ReceivingMessage simultaneously
* this map is used to indicate them with its index tokens.
*/
this.receivingMessages = new Map();
/**
* Supported candidate types. Below types are for both sending and receiving candidates.
* It means if when client receives candidate from STUN server, it sends to the server if candidate's protocol
* is in the list. Likely, when client receives remote candidate from server, it adds as ice candidate
* if candidate protocol is in the list below.
*/
this.candidateTypes = ["udp", "tcp"];
/**
* Method to call when there is an event happened
*/
this.callback = null;
/**
* Method to call when there is an error happened
*/
this.callbackError = null;
/**
* Flag to indicate if the stream is published or not after the connection fails
*/
this.reconnectIfRequiredFlag = true;
/**
* websocket url to connect
* @deprecated use websocketURL
*/
this.websocket_url = null;
/**
* Websocket URL
*/
this.websocketURL = null;
/**
* flag to initialize components in constructor
*/
this.initializeComponents = true;
/**
* Degradation Preference
*
* maintain-framerate, maintain-resolution, or balanced
*/
this.degradationPreference = "maintain-resolution";
/**
* PAY ATTENTION: The values of the above fields are provided as this constructor parameter.
* TODO: Also some other hidden parameters may be passed here
*/
for (var key in initialValues) {
Eif (initialValues.hasOwnProperty(key)) {
this[key] = initialValues[key];
}
}
Iif (this.websocketURL == null) {
this.websocketURL = this.websocket_url;
}
Iif (this.websocketURL == null) {
throw new Error("WebSocket URL is not defined. It's mandatory");
}
/**
* The html video tag for receiver is got here
*/
this.remoteVideo = this.remoteVideoElement || document.getElementById(this.remoteVideoId);
/**
* Keeps the sound meters for each connection. Its index is stream id
*/
this.soundMeters = new Array();
/**
* Keeps the current audio level for each playing streams in conference mode
*/
this.soundLevelList = new Array();
/**
* This is the event listeners that WebRTC Adaptor calls when there is a new event happened
*/
this.eventListeners = new Array();
/**
* This is the error event listeners that WebRTC Adaptor calls when there is an error happened
*/
this.errorEventListeners = new Array();
/**
* This is token that is being used to publish the stream. It's added here to use in reconnect scenario
*/
this.publishToken = null;
/**
* subscriber id that is being used to publish the stream. It's added here to use in reconnect scenario
*/
this.publishSubscriberId = null;
/**
* subscriber code that is being used to publish the stream. It's added here to use in reconnect scenario
*/
this.publishSubscriberCode = null;
/**
* This is the stream name that is being published. It's added here to use in reconnect scenario
*/
this.publishStreamName = null;
/**
* This is the stream id of the main track that the current publishStreamId is going to be subtrack of it. It's added here to use in reconnect scenario
*/
this.publishMainTrack = null;
/**
* This is the metadata that is being used to publish the stream. It's added here to use in reconnect scenario
*/
this.publishMetaData = null;
/**
* This is the role for selective subtrack playback. It's added here to use in reconnect scenario
*/
this.publishRole = null;
/**
* This is the token to play the stream. It's added here to use in reconnect scenario
*/
this.playToken = null;
/**
* This is the room id to play the stream. It's added here to use in reconnect scenario
* This approach is old conferencing. It's better to use multi track conferencing
*/
this.playRoomId = null;
/**
* These are enabled tracks to play the stream. It's added here to use in reconnect scenario
*/
this.playEnableTracks = null;
/**
* This is the subscriber Id to play the stream. It's added here to use in reconnect scenario
*/
this.playSubscriberId = null;
/**
* This is the subscriber code to play the stream. It's added here to use in reconnect scenario
*/
this.playSubscriberCode = null;
/**
* This is the meta data to play the stream. It's added here to use in reconnect scenario
*/
this.playMetaData = null;
/**
* This is the role for selective subtrack playback. It's added here to use in reconnect scenario
*/
this.playRole = null;
/**
* This is the time info for the last reconnection attempt
*/
this.lastReconnectiontionTrialTime = 0;
/**
* All media management works for teh local stream are made by @MediaManager class.
* for details please check @MediaManager
*/
this.mediaManager = new MediaManager({
userParameters: initialValues,
webRTCAdaptor: this,
callback: (info, obj) => {
this.notifyEventListeners(info, obj)
},
callbackError: (error, message) => {
this.notifyErrorEventListeners(error, message)
},
getSender: (streamId, type) => {
return this.getSender(streamId, type)
},
});
//Initialize the local stream (if needed) and web socket connection
Eif (this.initializeComponents) {
this.initialize();
}
}
/**
* Init plugins
*/
initPlugins() {
WebRTCAdaptor.pluginInitMethods.forEach((initMethod) => {
initMethod(this);
});
}
/**
* Add event listener to be notified. This is generally for plugins
* @param {*} listener
*/
addEventListener(listener) {
this.eventListeners.push(listener);
}
/**
* Add error event listener to be notified. Thisis generally for plugins
* @param {*} errorListener
*/
addErrorEventListener(errorListener) {
this.errorEventListeners.push(errorListener);
}
/**
* Notify event listeners and callback method
* @param {*} info
* @param {*} obj
*/
notifyEventListeners(info, obj) {
this.eventListeners.forEach((listener) => {
listener(info, obj);
});
Iif (this.callback != null) {
this.callback(info, obj);
}
}
/**
* Notify error event listeners and callbackError method
* @param {*} error
* @param {*} message
*/
notifyErrorEventListeners(error, message) {
this.errorEventListeners.forEach((listener) => {
listener(error, message);
});
if (this.callbackError != null) {
this.callbackError(error, message);
}
}
/**
* Called by constuctor to
* -check local stream unless it is in play mode
* -start websocket connection
*/
initialize() {
Iif (!this.isPlayMode && !this.onlyDataChannel && this.mediaManager.localStream == null)
{
//we need local stream because it not a play mode
return this.mediaManager.initLocalStream().then(() => {
this.initPlugins();
this.checkWebSocketConnection();
return new Promise((resolve, reject) => {
resolve("Wait 'initialized' callback from websocket");
});
}).catch(error => {
Logger.warn(error);
throw error;
});
}
return new Promise((resolve, reject) => {
this.initPlugins();
this.checkWebSocketConnection();
resolve("Wait 'initialized' callback from websocket");
});
}
/**
* Called to start a new WebRTC stream. AMS responds with start message.
* Parameters:
* @param {string} streamId : unique id for the stream
* @param {string=} [token] : required if any stream security (token control) enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Stream-Security-Documentation
* @param {string=} [subscriberId] : required if TOTP enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Time-based-One-Time-Password-(TOTP)
* @param {string=} [subscriberCode] : required if TOTP enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Time-based-One-Time-Password-(TOTP)
* @param {string=} [streamName] : required if you want to set a name for the stream
* @param {string=} [mainTrack] : required if you want to start the stream as a subtrack for a main stream which has id of this parameter.
* Check:https://antmedia.io/antmediaserver-webrtc-multitrack-playing-feature/
* !!! for multitrack conference set this value with roomName
* @param {string=} [metaData] : a free text information for the stream to AMS. It is provided to Rest methods by the AMS
* @param {string=} [role] : role for the stream. It is used for selective forwarding of subtracks in conference mode.
*/
publish(streamId, token, subscriberId, subscriberCode, streamName, mainTrack, metaData, role) {
//TODO: should refactor the repeated code
this.publishStreamId = streamId;
this.mediaManager.publishStreamId = streamId;
this.publishToken = token;
this.publishSubscriberId = subscriberId;
this.publishSubscriberCode = subscriberCode;
this.publishStreamName = streamName;
this.publishMainTrack = mainTrack;
this.publishMetaData = metaData;
this.publishRole = role;
if (this.onlyDataChannel) {
this.sendPublishCommand(streamId, token, subscriberId, subscriberCode, streamName, mainTrack, metaData, role, false, false);
}
//If it started with playOnly mode and wants to publish now
else if (this.mediaManager.localStream == null) {
this.mediaManager.initLocalStream().then(() => {
let videoEnabled = false;
let audioEnabled = false;
if (this.mediaManager.localStream != null) {
videoEnabled = this.mediaManager.localStream.getVideoTracks().length > 0;
audioEnabled = this.mediaManager.localStream.getAudioTracks().length > 0;
}
this.sendPublishCommand(streamId, token, subscriberId, subscriberCode, streamName, mainTrack, metaData, role, videoEnabled, audioEnabled)
}).catch(error => {
Logger.warn(error);
throw error;
});
} else {
let videoEnabled = this.mediaManager.localStream.getVideoTracks().length > 0;
let audioEnabled = this.mediaManager.localStream.getAudioTracks().length > 0;
this.sendPublishCommand(streamId, token, subscriberId, subscriberCode, streamName, mainTrack, metaData, role, videoEnabled, audioEnabled);
}
//init peer connection for reconnectIfRequired
this.initPeerConnection(streamId, "publish");
setTimeout(() => {
//check if it is connected or not
//this resolves if the server responds with some error message
if (this.iceConnectionState(this.publishStreamId) != "checking" && this.iceConnectionState(this.publishStreamId) != "connected" && this.iceConnectionState(this.publishStreamId) != "completed") {
//if it is not connected, try to reconnect
this.reconnectIfRequired(0);
}
}, 3000);
}
sendPublishCommand(streamId, token, subscriberId, subscriberCode, streamName, mainTrack, metaData, role, videoEnabled, audioEnabled) {
let jsCmd = {
command: "publish",
streamId: streamId,
token: token,
subscriberId: (typeof subscriberId !== undefined && subscriberId != null) ? subscriberId : "",
subscriberCode: (typeof subscriberCode !== undefined && subscriberCode != null) ? subscriberCode : "",
streamName: (typeof streamName !== undefined && streamName != null) ? streamName : "",
mainTrack: (typeof mainTrack !== undefined && mainTrack != null) ? mainTrack : "",
video: videoEnabled,
audio: audioEnabled,
metaData: (typeof metaData !== undefined && metaData != null) ? metaData : "",
role: (typeof role !== undefined && role != null) ? role : "",
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to join a room. AMS responds with joinedTheRoom message.
* Parameters:
* @param {string} roomName : unique id of the room
* @param {string=} streamId : unique id of the stream belongs to this participant
* @param {string=} mode : legacy for older implementation (default value)
* mcu for merging streams
* amcu: audio only conferences with mixed audio
*/
joinRoom(roomName, streamId, mode) {
this.roomName = roomName;
let jsCmd = {
command: "joinRoom",
room: roomName,
streamId: streamId,
mode: mode,
}
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to start a playing session for a stream. AMS responds with start message.
* Parameters:
* @param {string} streamId :(string) unique id for the stream that you want to play
* @param {string=} token :(string) required if any stream security (token control) enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Stream-Security-Documentation
* @param {string=} roomId :(string) required if this stream is belonging to a room participant
* @param {Array.<MediaStreamTrack>=} enableTracks :(array) required if the stream is a main stream of multitrack playing. You can pass the the subtrack id list that you want to play.
* you can also provide a track id that you don't want to play by adding ! before the id.
* @param {string=} subscriberId :(string) required if TOTP enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Time-based-One-Time-Password-(TOTP)
* @param {string=} subscriberCode :(string) required if TOTP enabled. Check https://github.com/ant-media/Ant-Media-Server/wiki/Time-based-One-Time-Password-(TOTP)
* @param {string=} metaData :(string, json) a free text information for the stream to AMS. It is provided to Rest methods by the AMS
* @param {string=} [role] : role for the stream. It is used for selective forwarding of subtracks in conference mode.
*/
play(streamId, token, roomId, enableTracks, subscriberId, subscriberCode, metaData, role) {
this.playStreamId.push(streamId);
this.playToken = token;
this.playRoomId = roomId;
this.playEnableTracks = enableTracks;
this.playSubscriberId = subscriberId;
this.playSubscriberCode = subscriberCode;
this.playMetaData = metaData;
this.playRole = role;
let jsCmd =
{
command: "play",
streamId: streamId,
token: typeof token !== undefined && token != null ? token : "",
room: typeof roomId !== undefined && roomId != null ? roomId : "",
trackList: typeof enableTracks !== undefined && enableTracks != null ? enableTracks : [],
subscriberId: typeof subscriberId !== undefined && subscriberId != null ? subscriberId : "",
subscriberCode: typeof subscriberCode !== undefined && subscriberId != null ? subscriberCode : "",
viewerInfo: typeof metaData !== undefined && metaData != null ? metaData : "",
role: (typeof role !== undefined && role != null) ? role : "",
}
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
//init peer connection for reconnectIfRequired
this.initPeerConnection(streamId, "play");
setTimeout(() => {
//check if it is connected or not
//this resolves if the server responds with some error message
if (this.iceConnectionState(streamId) != "checking" &&
this.iceConnectionState(streamId) != "connected" &&
this.iceConnectionState(streamId) != "completed")
{
//if it is not connected, try to reconnect
this.reconnectIfRequired(0);
}
}, 3000);
}
/**
* Reconnects to the stream if it is not stopped on purpose
* @param {number} [delayMs]
* @returns
*/
reconnectIfRequired(delayMs=3000)
{
if (this.reconnectIfRequiredFlag)
{
//It's important to run the following methods after 3000 ms because the stream may be stopped by the user in the meantime
if (delayMs > 0)
{
setTimeout(() => {
this.tryAgain();
}, delayMs);
}
else {
this.tryAgain()
}
}
}
tryAgain() {
const now = Date.now();
//to prevent too many trial from different paths
if(now - this.lastReconnectiontionTrialTime < 3000) {
return;
}
this.lastReconnectiontionTrialTime = now;
//reconnect publish
//if remotePeerConnection has a peer connection for the stream id, it means that it is not stopped on purpose
if (this.remotePeerConnection[this.publishStreamId] != null &&
//check connection status to not stop streaming an active stream
this.iceConnectionState(this.publishStreamId) != "checking" &&
this.iceConnectionState(this.publishStreamId) != "connected" &&
this.iceConnectionState(this.publishStreamId) != "completed")
{
// notify that reconnection process started for publish
this.notifyEventListeners("reconnection_attempt_for_publisher", this.publishStreamId);
this.stop(this.publishStreamId);
setTimeout(() => {
//publish about some time later because server may not drop the connection yet
//it may trigger already publishing error
Logger.log("Trying publish again for stream: " + this.publishStreamId);
this.publish(this.publishStreamId, this.publishToken, this.publishSubscriberId, this.publishSubscriberCode, this.publishStreamName, this.publishMainTrack, this.publishMetaData, this.publishRole);
}, 500);
}
//reconnect play
for (var index in this.playStreamId)
{
let streamId = this.playStreamId[index];
if (this.remotePeerConnection[streamId] != "null" &&
//check connection status to not stop streaming an active stream
this.iceConnectionState(streamId) != "checking" &&
this.iceConnectionState(streamId) != "connected" &&
this.iceConnectionState(streamId) != "completed")
{
// notify that reconnection process started for play
this.notifyEventListeners("reconnection_attempt_for_player", streamId);
Logger.log("It will try to play again for stream: " + streamId + " because it is not stopped on purpose")
this.stop(streamId);
setTimeout(() => {
//play about some time later because server may not drop the connection yet
//it may trigger already playing error
Logger.log("Trying play again for stream: " + streamId);
this.play(streamId, this.playToken, this.playRoomId, this.playEnableTracks, this.playSubscriberId, this.playSubscriberCode, this.playMetaData, this.playRole);
}, 500);
}
}
}
/**
* Called to stop a publishing/playing session for a stream. AMS responds with publishFinished or playFinished message.
* Parameters:
* @param {string} streamId : unique id for the stream that you want to stop publishing or playing
*/
stop(streamId) {
//stop is called on purpose and it deletes the peer connection from remotePeerConnections
this.closePeerConnection(streamId);
if (this.webSocketAdaptor != null && this.webSocketAdaptor.isConnected()) {
let jsCmd = {
command: "stop",
streamId: streamId,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
}
/**
* Called to join a peer-to-peer mode session as peer. AMS responds with joined message.
* Parameters:
* @param {string} streamId : unique id for the peer-to-peer session
*/
join(streamId) {
let jsCmd = {
command: "join",
streamId: streamId,
multiPeer: this.isMultiPeer && this.multiPeerStreamId == null,
mode: this.isPlayMode ? "play" : "both",
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called by browser when a new track is added to WebRTC connetion. This is used to infor html pages with newStreamAvailable callback.
* Parameters:
* event: TODO
* streamId: unique id for the stream
*/
onTrack(event, streamId)
{
Logger.debug("onTrack for stream");
if (this.remoteVideo != null) {
if (this.remoteVideo.srcObject !== event.streams[0]) {
this.remoteVideo.srcObject = event.streams[0];
Logger.debug('Received remote stream');
}
}
else {
var dataObj = {
stream: event.streams[0],
track: event.track,
streamId: streamId,
trackId: this.idMapping[streamId][event.transceiver.mid],
}
this.notifyEventListeners("newTrackAvailable", dataObj);
//deprecated. Listen newTrackAvailable in callback. It's kept for backward compatibility
this.notifyEventListeners("newStreamAvailable", dataObj);
}
}
/**
* Called to leave from a conference room. AMS responds with leavedTheRoom message.
* Parameters:
* @param {string} roomName : unique id for the conference room
*/
leaveFromRoom(roomName) {
for (var key in this.remotePeerConnection) {
this.closePeerConnection(key);
}
this.roomName = roomName;
var jsCmd = {
command: "leaveFromRoom",
room: roomName,
};
Logger.debug("leave request is sent for " + roomName);
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to leave from a peer-to-peer mode session. AMS responds with leaved message.
* Parameters:
* @param {string} streamId : unique id for the peer-to-peer session
*/
leave(streamId) {
var jsCmd = {
command: "leave",
streamId: this.isMultiPeer && this.multiPeerStreamId != null ? this.multiPeerStreamId : streamId,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
this.closePeerConnection(streamId);
this.multiPeerStreamId = null;
}
/**
* Called to get a stream information for a specific stream. AMS responds with streamInformation message.
* Parameters:
* @param {string} streamId : unique id for the stream that you want to get info about
*/
getStreamInfo(streamId) {
let jsCmd = {
command: "getStreamInfo",
streamId: streamId,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to get the list of video track assignments. AMS responds with the videoTrackAssignmentList message.
* Parameters:
* @param {string} streamId : unique id for the stream that you want to get info about
*/
requestVideoTrackAssignments(streamId) {
let jsCmd = {
command: "getVideoTrackAssignmentsCommand",
streamId: streamId,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to get the broadcast object for a specific stream. AMS responds with the broadcastObject callback.
* Parameters:
* @param {string} streamId : unique id for the stream that you want to get info about
*/
getBroadcastObject(streamId) {
let jsCmd = {
command: "getBroadcastObject",
streamId: streamId,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to update the meta information for a specific stream.
* Parameters:
* @param {string} streamId : unique id for the stream that you want to update MetaData
* @param {string} metaData : new free text information for the stream
*/
updateStreamMetaData(streamId, metaData) {
var jsCmd = {
command: "updateStreamMetaData",
streamId: streamId,
metaData: metaData,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to get the room information for a specific room. AMS responds with roomInformation message
* which includes the ids and names of the streams in that room.
* If there is no active streams in the room, AMS returns error `no_active_streams_in_room` in error callback
* Parameters:
* @param {string} roomName : unique id for the room that you want to get info about
* @param {string} streamId : unique id for the stream that is streamed by this @WebRTCAdaptor
*/
getRoomInfo(roomName, streamId) {
var jsCmd = {
command: "getRoomInfo",
streamId: streamId,
room: roomName,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to get the subtracks for a specific maintrack. AMS responds with the subtrackList callback.
* Parameters:
* @param {string} streamId : main track id
* @param {string} role : filter the subtracks with the role
* @param {number} offset : offset for the subtrack list
* @param {number} size : size for the subtrack list
*/
getSubtracks(streamId, role, offset, size) {
let jsCmd = {
command: "getSubtracks",
streamId: streamId,
role: role,
offset: offset,
size: size,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to enable/disable data flow from the AMS for a specific track under a main track.
* Parameters:
* @param {string} mainTrackId : unique id for the main stream
* @param {string} trackId : unique id for the track that you want to enable/disable data flow for
* @param {boolean} enabled : true or false
*/
enableTrack(mainTrackId, trackId, enabled) {
var jsCmd = {
command: "enableTrack",
streamId: mainTrackId,
trackId: trackId,
enabled: enabled,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to get the track ids under a main stream. AMS responds with trackList message.
* Parameters:
* @param {string} streamId : unique id for the main stream
* @param {string=} [token] : not used
* TODO: check this function
*/
getTracks(streamId, token) {
this.playStreamId.push(streamId);
var jsCmd =
{
command: "getTrackList",
streamId: streamId,
token: token,
}
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called by WebSocketAdaptor when a new ice candidate is received from AMS.
* Parameters:
* event: TODO
* streamId: unique id for the stream
*/
iceCandidateReceived(event, streamId) {
if (event.candidate) {
var protocolSupported = false;
if (event.candidate.candidate == "") {
//event candidate can be received and its value can be "".
//don't compare the protocols
protocolSupported = true;
} else if (typeof event.candidate.protocol == "undefined") {
this.candidateTypes.forEach(element => {
if (event.candidate.candidate.toLowerCase().includes(element)) {
protocolSupported = true;
}
});
} else {
protocolSupported = this.candidateTypes.includes(event.candidate.protocol.toLowerCase());
}
if (protocolSupported) {
var jsCmd = {
command: "takeCandidate",
streamId: streamId,
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate
};
if (this.debug) {
Logger.debug("sending ice candiate for stream Id " + streamId);
Logger.debug(JSON.stringify(event.candidate));
}
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
} else {
Logger.debug("Candidate's protocol(full sdp: " + event.candidate.candidate + ") is not supported. Supported protocols: " + this.candidateTypes);
if (event.candidate.candidate != "") { //
this.notifyErrorEventListeners("protocol_not_supported", "Support protocols: " + this.candidateTypes.toString() + " candidate: " + event.candidate.candidate);
}
}
} else {
Logger.debug("No event.candidate in the iceCandidate event");
}
}
/**
* Called internally to sanitize the text if it contains script to prevent xss
* @param text
* @returns {*}
*/
sanitizeHTML(text) {
if(text.includes("script"))
return text.replace(/</g, "<").replace(/>/g, ">");
return text
}
/**
* Called internally to initiate Data Channel.
* Note that Data Channel should be enabled fromAMS settings.
* @param {string} streamId : unique id for the stream
* @param {*} dataChannel : provided by PeerConnection
*/
initDataChannel(streamId, dataChannel) {
dataChannel.onerror = (error) => {
Logger.debug("Data Channel Error:", error);
var obj = {
streamId: streamId,
error: error
};
Logger.debug("channel status: ", dataChannel.readyState);
if (dataChannel.readyState != "closed") {
this.notifyErrorEventListeners("data_channel_error", obj);
}
};
dataChannel.onmessage = (event) => {
var obj = {
streamId: streamId,
data: event.data,
};
var data = obj.data;
if (typeof data === 'string' || data instanceof String) {
obj.data = this.sanitizeHTML(obj.data)
this.notifyEventListeners("data_received", obj);
} else {
var length = data.length || data.size || data.byteLength;
var view = new Int32Array(data, 0, 1);
var token = view[0];
var msg = this.receivingMessages[token];
if (msg == undefined) {
var view = new Int32Array(data, 0, 2);
var size = view[1];
msg = new ReceivingMessage(size);
this.receivingMessages[token] = msg;
if (length > 8) {
Logger.debug("something went wrong in msg receiving");
}
return;
}
var rawData = data.slice(4, length);
var dataView = new Uint8Array(msg.data);
dataView.set(new Uint8Array(rawData), msg.received, length - 4);
msg.received += length - 4;
if (msg.size == msg.received) {
obj.data = msg.data;
this.notifyEventListeners("data_received", obj);
}
}
};
dataChannel.onopen = () => {
this.remotePeerConnection[streamId].dataChannel = dataChannel;
Logger.debug("Data channel is opened");
this.notifyEventListeners("data_channel_opened", streamId)
};
dataChannel.onclose = () => {
Logger.debug("Data channel is closed");
this.notifyEventListeners("data_channel_closed", streamId);
};
}
/**
* Called internally to initiate PeerConnection.
* @param {string} streamId : unique id for the stream
* @param {string} dataChannelMode : can be "publish" , "play" or "peer" based on this it is decided which way data channel is created
*/
initPeerConnection(streamId, dataChannelMode) {
//null == undefined -> it's true
//null === undefined -> it's false
if (this.remotePeerConnection[streamId] == null) {
let closedStreamId = streamId;
Logger.debug("stream id in init peer connection: " + streamId + " close stream id: " + closedStreamId);
this.remotePeerConnection[streamId] = new RTCPeerConnection(this.peerconnection_config);
this.remoteDescriptionSet[streamId] = false;
this.iceCandidateList[streamId] = new Array();
if (!this.playStreamId.includes(streamId)) {
if (this.mediaManager.localStream != null) {
this.mediaManager.localStream.getTracks().forEach(track => {
let rtpSender = this.remotePeerConnection[streamId].addTrack(track, this.mediaManager.localStream);
if (track.kind == 'video')
{
let parameters = rtpSender.getParameters();
parameters.degradationPreference = this.degradationPreference;
rtpSender.setParameters(parameters).then(() => {
Logger.info("Degradation Preference is set to " + this.degradationPreference);
}).catch((err) => {
Logger.warn("Degradation Preference cannot be set to " + this.degradationPreference)
});
}
//
//parameters.degradationPreference
});
}
}
this.remotePeerConnection[streamId].onicecandidate = event => {
this.iceCandidateReceived(event, closedStreamId);
}
this.remotePeerConnection[streamId].ontrack = event => {
this.onTrack(event, closedStreamId);
}
this.remotePeerConnection[streamId].onnegotiationneeded = event => {
Logger.debug("onnegotiationneeded");
}
if (this.dataChannelEnabled) {
// skip initializing data channel if it is disabled
if (dataChannelMode == "publish") {
//open data channel if it's publish mode peer connection
const dataChannelOptions = {
ordered: true,
};
if (this.remotePeerConnection[streamId].createDataChannel) {
var dataChannel = this.remotePeerConnection[streamId].createDataChannel(streamId, dataChannelOptions);
this.initDataChannel(streamId, dataChannel);
} else {
Logger.warn("CreateDataChannel is not supported");
}
} else if (dataChannelMode == "play") {
//in play mode, server opens the data channel
this.remotePeerConnection[streamId].ondatachannel = ev => {
this.initDataChannel(streamId, ev.channel);
};
} else {
//for peer mode do both for now
const dataChannelOptions = {
ordered: true,
};
if (this.remotePeerConnection[streamId].createDataChannel) {
var dataChannelPeer = this.remotePeerConnection[streamId].createDataChannel(streamId, dataChannelOptions);
this.initDataChannel(streamId, dataChannelPeer);
this.remotePeerConnection[streamId].ondatachannel = ev => {
this.initDataChannel(streamId, ev.channel);
};
} else {
Logger.warn("CreateDataChannel is not supported");
}
}
}
this.remotePeerConnection[streamId].oniceconnectionstatechange = event => {
var obj = {state: this.remotePeerConnection[streamId].iceConnectionState, streamId: streamId};
if (obj.state == "failed" || obj.state == "disconnected" || obj.state == "closed") {
this.reconnectIfRequired(3000);
}
this.notifyEventListeners("ice_connection_state_changed", obj);
//
if (!this.isPlayMode && !this.playStreamId.includes(streamId)) {
if (this.remotePeerConnection[streamId].iceConnectionState == "connected") {
this.mediaManager.changeBandwidth(this.mediaManager.bandwidth, streamId).then(() => {
Logger.debug("Bandwidth is changed to " + this.mediaManager.bandwidth);
})
.catch(e => Logger.warn(e));
}
}
}
}
return this.remotePeerConnection[streamId];
}
/**
* Called internally to close PeerConnection.
* @param {string} streamId : unique id for the stream
*/
closePeerConnection(streamId) {
var peerConnection = this.remotePeerConnection[streamId];
if (peerConnection != null) {
this.remotePeerConnection[streamId] = null;
delete this.remotePeerConnection[streamId];
if (peerConnection.dataChannel != null) {
peerConnection.dataChannel.close();
}
if (peerConnection.signalingState != "closed") {
peerConnection.close();
}
var playStreamIndex = this.playStreamId.indexOf(streamId);
if (playStreamIndex != -1) {
this.playStreamId.splice(playStreamIndex, 1);
}
}
//this is for the stats
if (this.remotePeerConnectionStats[streamId] != null) {
clearInterval(this.remotePeerConnectionStats[streamId].timerId);
delete this.remotePeerConnectionStats[streamId];
}
if (this.soundMeters[streamId] != null) {
delete this.soundMeters[streamId];
}
}
/**
* Called to get the signalling state for a stream.
* This information can be used for error handling.
* Check: https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
* @param {string} streamId : unique id for the stream
*/
signallingState(streamId) {
if (this.remotePeerConnection[streamId] != null) {
return this.remotePeerConnection[streamId].signalingState;
}
return null;
}
/**
* Called to get the ice connection state for a stream.
* This information can be used for error handling.
* Check: https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/iceConnectionState
* @param {string} streamId : unique id for the stream
*/
iceConnectionState(streamId) {
if (this.remotePeerConnection[streamId] != null) {
return this.remotePeerConnection[streamId].iceConnectionState;
}
return null;
}
/**
* Called by browser when Local Configuration (SDP) is created successfully.
* It is set as LocalDescription first then sent to AMS.
* @param {object} configuration : created Local Configuration (SDP)
* @param {string} streamId : unique id for the stream
*/
gotDescription(configuration, streamId) {
this.remotePeerConnection[streamId]
.setLocalDescription(configuration)
.then(responose => {
Logger.debug("Set local description successfully for stream Id " + streamId);
var jsCmd = {
command: "takeConfiguration",
streamId: streamId,
type: configuration.type,
sdp: configuration.sdp
};
Logger.debug("setLocalDescription:"+configuration.sdp);
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}).catch((error) => {
Logger.error("Cannot set local description. Error is: " + error);
});
}
/**
* Called by WebSocketAdaptor when Remote Configuration (SDP) is received from AMS.
* It is set as RemoteDescription first then if @iceCandidateList has candidate that
* is received bfore this message, it is added as ice candidate.
* @param {object} configuration : received Remote Configuration (SDP)
* @param {string} idOfStream : unique id for the stream
* @param {string} typeOfConfiguration
* @param {string} idMapping : stream id and track id (which is provided in SDP) mapping in MultiTrack Playback and conference.
* It is recorded to match stream id as new tracks are added with @onTrack
*/
takeConfiguration(idOfStream, configuration, typeOfConfiguration, idMapping) {
var streamId = idOfStream
var type = typeOfConfiguration;
var conf = configuration;
var isTypeOffer = (type == "offer");
var dataChannelMode = "publish";
if (isTypeOffer) {
dataChannelMode = "play";
}
this.idMapping[streamId] = idMapping;
this.initPeerConnection(streamId, dataChannelMode);
Logger.debug("setRemoteDescription:" + conf);
this.remotePeerConnection[streamId].setRemoteDescription(new RTCSessionDescription({
sdp: conf,
type: type
})).then(response => {
if (this.debug) {
Logger.debug("set remote description is succesfull with response: " + response + " for stream : "
+ streamId + " and type: " + type);
Logger.debug(conf);
}
this.remoteDescriptionSet[streamId] = true;
var length = this.iceCandidateList[streamId].length;
Logger.debug("Ice candidate list size to be added: " + length);
for (var i = 0; i < length; i++) {
this.addIceCandidate(streamId, this.iceCandidateList[streamId][i]);
}
this.iceCandidateList[streamId] = [];
if (isTypeOffer) {
//SDP constraints may be different in play mode
Logger.debug("try to create answer for stream id: " + streamId);
this.remotePeerConnection[streamId].createAnswer(this.sdp_constraints)
.then(configuration => {
Logger.debug("created answer for stream id: " + streamId);
//support for stereo
configuration.sdp = configuration.sdp.replace("useinbandfec=1", "useinbandfec=1; stereo=1");
this.gotDescription(configuration, streamId);
})
.catch((error) => {
Logger.error("create answer error :" + error);
});
}
}).catch((error) => {
if (this.debug) {
Logger.error("set remote description is failed with error: " + error);
}
if (error.toString().indexOf("InvalidAccessError") > -1 || error.toString().indexOf("setRemoteDescription") > -1) {
/**
* This error generally occurs in codec incompatibility.
* AMS for a now supports H.264 codec. This error happens when some browsers try to open it from VP8.
*/
this.notifyErrorEventListeners("notSetRemoteDescription");
}
});
}
/**
* Called by WebSocketAdaptor when new ice candidate is received from AMS.
* If Remote Description (SDP) is already set, the candidate is added immediately,
* otherwise stored in @iceCandidateList to add after Remote Description (SDP) set.
* @param {string} idOfTheStream : unique id for the stream
* @param {number|null} tmpLabel : sdpMLineIndex
* @param {string} tmpCandidate : ice candidate
*/
takeCandidate(idOfTheStream, tmpLabel, tmpCandidate) {
var streamId = idOfTheStream;
var label = tmpLabel;
var candidateSdp = tmpCandidate;
var candidate = new RTCIceCandidate({
sdpMLineIndex: label,
candidate: candidateSdp
});
var dataChannelMode = "peer";
this.initPeerConnection(streamId, dataChannelMode);
Logger.debug("takeCandidate:" + candidateSdp)
if (this.remoteDescriptionSet[streamId] == true) {
this.addIceCandidate(streamId, candidate);
} else {
Logger.debug("Ice candidate is added to list because remote description is not set yet");
this.iceCandidateList[streamId].push(candidate);
}
};
/**
* Called internally to add the Ice Candidate to PeerConnection
* @param {string} streamId : unique id for the stream
* @param {object} candidate : ice candidate
*/
addIceCandidate(streamId, candidate) {
var protocolSupported = false;
if (candidate.candidate == "") {
//candidate can be received and its value can be "".
//don't compare the protocols
protocolSupported = true;
} else if (typeof candidate.protocol == "undefined") {
this.candidateTypes.forEach(element => {
if (candidate.candidate.toLowerCase().includes(element)) {
protocolSupported = true;
}
});
} else {
protocolSupported = this.candidateTypes.includes(candidate.protocol.toLowerCase());
}
if (protocolSupported) {
this.remotePeerConnection[streamId].addIceCandidate(candidate)
.then(response => {
if (this.debug) {
Logger.debug("Candidate is added for stream " + streamId);
}
})
.catch((error) => {
Logger.error("ice candiate cannot be added for stream id: " + streamId + " error is: " + error);
Logger.error(candidate);
});
} else {
if (this.debug) {
Logger.debug("Candidate's protocol(" + candidate.protocol + ") is not supported." +
"Candidate: " + candidate.candidate + " Supported protocols:" + this.candidateTypes);
}
}
};
/**
* Called by WebSocketAdaptor when start message is received //TODO: may be changed. this logic shouldn't be in WebSocketAdaptor
* @param {string} idOfStream : unique id for the stream
*/
startPublishing(idOfStream) {
let streamId = idOfStream;
let peerConnection = this.initPeerConnection(streamId, "publish");
//this.remotePeerConnection[streamId]
peerConnection.createOffer(this.sdp_constraints)
.then(configuration => {
this.gotDescription(configuration, streamId);
})
.catch((error) => {
Logger.error("create offer error for stream id: " + streamId + " error: " + error);
});
}
/**
* Toggle video track on the server side.
*
* @param {string} streamId : is the id of the stream
* @param {string} trackId : is the id of the track. streamId is also one of the trackId of the stream. If you are having just a single track on your
* stream, you need to give streamId as trackId parameter as well.
* @param {boolean} enabled : is the enable/disable video track. If it's true, server sends video track. If it's false, server does not send video
*/
toggleVideo(streamId, trackId, enabled) {
let jsCmd = {
command: "toggleVideo",
streamId: streamId,
trackId: trackId,
enabled: enabled,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Toggle audio track on the server side.
*
* @param {string} streamId : is the id of the stream
* @param {string} trackId : is the id of the track. streamId is also one of the trackId of the stream. If you are having just a single track on your
* stream, you need to give streamId as trackId parameter as well.
* @param {boolean} enabled : is the enable/disable video track. If it's true, server sends audio track. If it's false, server does not send audio
*
*/
toggleAudio(streamId, trackId, enabled) {
var jsCmd = {
command: "toggleAudio",
streamId: streamId,
trackId: trackId,
enabled: enabled,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to get statistics for a PeerConnection. It can be publisher or player.
*
* @param {string} streamId : unique id for the stream
*/
getStats(streamId) {
Logger.debug("peerstatsgetstats = " + this.remotePeerConnectionStats[streamId]);
return new Promise((resolve, reject) => {
this.remotePeerConnection[streamId].getStats(null).then(stats => {
var bytesReceived = -1;
var videoPacketsLost = -1;
var audioPacketsLost = -1;
var fractionLost = -1;
var currentTime = -1;
var bytesSent = -1;
var videoPacketsSent = -1;
var audioPacketsSent = -1;
var audioLevel = -1;
var qlr = "";
var framesEncoded = -1;
var width = -1;
var height = -1;
var fps = -1;
var frameWidth = -1;
var frameHeight = -1;
var videoRoundTripTime = -1;
var videoJitter = -1;
var audioRoundTripTime = -1;
var audioJitter = -1;
var framesDecoded = -1;
var framesDropped = -1;
var framesReceived = -1;
var audioJitterAverageDelay = -1;
var videoJitterAverageDelay = -1;
var availableOutgoingBitrate = Infinity;
var inboundRtp = [];
stats.forEach(value => {
//Logger.debug(value);
if (value.type == "inbound-rtp" && typeof value.kind != "undefined") {
let inboundRtpObj = {};
inboundRtpObj.trackIdentifier = value.trackIdentifier;
bytesReceived += value.bytesReceived;
if (value.kind == "audio") {
audioPacketsLost = value.packetsLost;
inboundRtpObj.audioPacketsLost = value.packetsLost;
} else if (value.kind == "video") {
videoPacketsLost = value.packetsLost;
inboundRtpObj.videoPacketsLost = value.packetsLost;
inboundRtpObj.framesDropped = value.framesDropped;
inboundRtpObj.framesDecoded = value.framesDecoded;
inboundRtpObj.framesPerSecond = value.framesPerSecond;
}
inboundRtpObj.bytesReceived = value.bytesReceived;
inboundRtpObj.jitterBufferDelay = value.jitterBufferDelay;
inboundRtpObj.lastPacketReceivedTimestamp = value.lastPacketReceivedTimestamp;
fractionLost += value.fractionLost;
inboundRtpObj.fractionLost = value.fractionLost;
currentTime = value.timestamp;
inboundRtpObj.currentTime = value.timestamp;
if (typeof value.frameWidth != "undefined") {
frameWidth = value.frameWidth;
inboundRtpObj.frameWidth = value.frameWidth;
}
if (typeof value.frameHeight != "undefined") {
frameHeight = value.frameHeight;
inboundRtpObj.frameHeight = value.frameHeight;
}
if (typeof value.framesDecoded != "undefined") {
framesDecoded = value.framesDecoded;
inboundRtpObj.framesDecoded = value.framesDecoded;
}
if (typeof value.framesDropped != "undefined") {
framesDropped = value.framesDropped;
inboundRtpObj.framesDropped = value.framesDropped;
}
if (typeof value.framesReceived != "undefined") {
framesReceived = value.framesReceived;
inboundRtpObj.framesReceived = value.framesReceived;
}
inboundRtp.push(inboundRtpObj);
} else if (value.type == "outbound-rtp") {//TODO: SPLIT AUDIO AND VIDEO BITRATES
if (value.kind == "audio") {
audioPacketsSent = value.packetsSent;
} else if (value.kind == "video") {
videoPacketsSent = value.packetsSent;
frameWidth = value.frameWidth;
frameHeight = value.frameHeight;
}
bytesSent += value.bytesSent
currentTime = value.timestamp
qlr = value.qualityLimitationReason;
if (value.framesEncoded != null) { //audio tracks are undefined here
framesEncoded += value.framesEncoded;
}
} else if (value.type == "track" && typeof value.kind != "undefined" && value.kind == "audio") {
if (typeof value.audioLevel != "undefined") {
audioLevel = value.audioLevel;
}
if (typeof value.jitterBufferDelay != "undefined" && typeof value.jitterBufferEmittedCount != "undefined") {
audioJitterAverageDelay = value.jitterBufferDelay / value.jitterBufferEmittedCount;
}
} else if (value.type == "track" && typeof value.kind != "undefined" && value.kind == "video") {
if (typeof value.frameWidth != "undefined") {
frameWidth = value.frameWidth;
}
if (typeof value.frameHeight != "undefined") {
frameHeight = value.frameHeight;
}
if (typeof value.framesDecoded != "undefined") {
framesDecoded = value.framesDecoded;
}
if (typeof value.framesDropped != "undefined") {
framesDropped = value.framesDropped;
}
if (typeof value.framesReceived != "undefined") {
framesReceived = value.framesReceived;
}
if (typeof value.jitterBufferDelay != "undefined" && typeof value.jitterBufferEmittedCount != "undefined") {
videoJitterAverageDelay = value.jitterBufferDelay / value.jitterBufferEmittedCount;
}
}
else if (value.type == "remote-inbound-rtp" && typeof value.kind != "undefined") {
//this is coming when webrtc publishing
if (typeof value.packetsLost != "undefined") {
if (value.kind == "video") {
//this is the packetsLost for publishing
videoPacketsLost = value.packetsLost;
} else if (value.kind == "audio") {
//this is the packetsLost for publishing
audioPacketsLost = value.packetsLost;
}
}
if (typeof value.roundTripTime != "undefined") {
if (value.kind == "video") {
videoRoundTripTime = value.roundTripTime;
} else if (value.kind == "audio") {
audioRoundTripTime = value.roundTripTime;
}
}
if (typeof value.jitter != "undefined") {
if (value.kind == "video") {
videoJitter = value.jitter;
} else if (value.kind == "audio") {
audioJitter = value.jitter;
}
}
} else if (value.type == "media-source") {
if (value.kind == "video") { //returns video source dimensions, not necessarily dimensions being encoded by browser
width = value.width;
height = value.height;
fps = value.framesPerSecond;
}
}
else if(value.type == "candidate-pair" && value.state == "succeeded" && value.availableOutgoingBitrate !=undefined){
availableOutgoingBitrate = value.availableOutgoingBitrate/1000
}
});
if (typeof this.remotePeerConnectionStats[streamId] == 'undefined' || this.remotePeerConnectionStats[streamId] == null) {
this.remotePeerConnectionStats[streamId] = new PeerStats(streamId);
}
this.remotePeerConnectionStats[streamId].totalBytesReceived = bytesReceived;
this.remotePeerConnectionStats[streamId].videoPacketsLost = videoPacketsLost;
this.remotePeerConnectionStats[streamId].audioPacketsLost = audioPacketsLost;
this.remotePeerConnectionStats[streamId].fractionLost = fractionLost;
this.remotePeerConnectionStats[streamId].currentTime = currentTime;
this.remotePeerConnectionStats[streamId].totalBytesSent = bytesSent;
this.remotePeerConnectionStats[streamId].totalVideoPacketsSent = videoPacketsSent;
this.remotePeerConnectionStats[streamId].totalAudioPacketsSent = audioPacketsSent;
this.remotePeerConnectionStats[streamId].audioLevel = audioLevel;
this.remotePeerConnectionStats[streamId].qualityLimitationReason = qlr;
this.remotePeerConnectionStats[streamId].totalFramesEncoded = framesEncoded;
this.remotePeerConnectionStats[streamId].resWidth = width;
this.remotePeerConnectionStats[streamId].resHeight = height;
this.remotePeerConnectionStats[streamId].srcFps = fps;
this.remotePeerConnectionStats[streamId].frameWidth = frameWidth;
this.remotePeerConnectionStats[streamId].frameHeight = frameHeight;
this.remotePeerConnectionStats[streamId].videoRoundTripTime = videoRoundTripTime;
this.remotePeerConnectionStats[streamId].videoJitter = videoJitter;
this.remotePeerConnectionStats[streamId].audioRoundTripTime = audioRoundTripTime;
this.remotePeerConnectionStats[streamId].audioJitter = audioJitter;
this.remotePeerConnectionStats[streamId].framesDecoded = framesDecoded;
this.remotePeerConnectionStats[streamId].framesDropped = framesDropped;
this.remotePeerConnectionStats[streamId].framesReceived = framesReceived;
this.remotePeerConnectionStats[streamId].videoJitterAverageDelay = videoJitterAverageDelay;
this.remotePeerConnectionStats[streamId].audioJitterAverageDelay = audioJitterAverageDelay;
this.remotePeerConnectionStats[streamId].availableOutgoingBitrate = availableOutgoingBitrate;
this.remotePeerConnectionStats[streamId].inboundRtpList = inboundRtp;
this.notifyEventListeners("updated_stats", this.remotePeerConnectionStats[streamId]);
resolve(true);
}).catch(err=>{
resolve(false);
});
});
}
/**
* Called to start a periodic timer to get statistics periodically (5 seconds) for a specific stream.
*
* @param {string} streamId : unique id for the stream
* @param {number} periodMs : period in milliseconds. Default value is 5000 ms.
*/
enableStats(streamId, periodMs = 5000) {
if (this.remotePeerConnectionStats[streamId] == null) {
this.remotePeerConnectionStats[streamId] = new PeerStats(streamId);
this.remotePeerConnectionStats[streamId].timerId = setInterval(() => {
this.getStats(streamId);
}, periodMs);
}
}
/**
* Called to stop the periodic timer which is set by @enableStats
*
* @param {string} streamId : unique id for the stream
*/
disableStats(streamId) {
if (this.remotePeerConnectionStats[streamId] != null || typeof this.remotePeerConnectionStats[streamId] != 'undefined') {
clearInterval(this.remotePeerConnectionStats[streamId].timerId);
delete this.remotePeerConnectionStats[streamId];
}
}
/**
* Called to check and start Web Socket connection if it is not started
*/
checkWebSocketConnection() {
Eif (this.webSocketAdaptor == null || (this.webSocketAdaptor.isConnected() == false && this.webSocketAdaptor.isConnecting() == false))
{
Logger.debug("websocket url : " + this.websocketURL);
this.webSocketAdaptor = new WebSocketAdaptor({
websocket_url: this.websocketURL,
webrtcadaptor: this,
callback: (info, obj) => {
if (info == "closed") {
this.reconnectIfRequired();
}
this.notifyEventListeners(info, obj);
},
callbackError: (error, message) => {
this.notifyErrorEventListeners(error, message)
},
debug: this.debug
});
}
}
/**
* Called to stop Web Socket connection
* After calling this function, create new WebRTCAdaptor instance, don't use the the same object
* Because all streams are closed on server side as well when websocket connection is closed.
*/
closeWebSocket() {
for (var key in this.remotePeerConnection) {
this.closePeerConnection(key);
}
//free the remote peer connection by initializing again
this.remotePeerConnection = new Array();
this.webSocketAdaptor.close();
}
/**
* @param {string} streamId Called to send a text message to other peer in the peer-to-peer sessionnnection is closed.
* @param {*} definition
* @param {*} data
*/
peerMessage(streamId, definition, data) {
var jsCmd = {
command: "peerMessageCommand",
streamId: streamId,
definition: definition,
data: data,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to force AMS to send the video with the specified resolution in case of Adaptive Streaming (ABR) enabled.
* Normally the resolution is automatically determined by AMS according to the network condition.
* @param {string} streamId : unique id for the stream
* @param {*} resolution : default is auto. You can specify any height value from the ABR list.
*/
forceStreamQuality(streamId, resolution) {
var jsCmd = {
command: "forceStreamQuality",
streamId: streamId,
streamHeight: resolution
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called to send data via DataChannel. DataChannel should be enabled on AMS settings.
* @param {string} streamId : unique id for the stream
* @param {*} data : data that you want to send. It may be a text (may in Json format or not) or binary
*/
sendData(streamId, data) {
var CHUNK_SIZE = 16000;
if (this.remotePeerConnection[streamId] !== undefined) {
var dataChannel = this.remotePeerConnection[streamId].dataChannel;
if (dataChannel === undefined || dataChannel === null || typeof dataChannel === 'undefined') {
Logger.warn('dataChannel is null or undefined');
return;
} else if (dataChannel.readyState !== 'open') {
Logger.warn('dataChannel.readyState is not open: ' + dataChannel.readyState);
return;
}
var length = data.length || data.size || data.byteLength;
var sent = 0;
if (typeof data === 'string' || data instanceof String) {
dataChannel.send(data);
} else {
var token = Math.floor(Math.random() * 999999);
let header = new Int32Array(2);
header[0] = token;
header[1] = length;
dataChannel.send(header);
var sent = 0;
while (sent < length) {
var size = Math.min(length - sent, CHUNK_SIZE);
var buffer = new Uint8Array(size + 4);
var tokenArray = new Int32Array(1);
tokenArray[0] = token;
buffer.set(new Uint8Array(tokenArray.buffer, 0, 4), 0);
var chunk = data.slice(sent, sent + size);
buffer.set(new Uint8Array(chunk), 4);
sent += size;
dataChannel.send(buffer);
}
}
} else {
Logger.warn("Send data is called for undefined peer connection with stream id: " + streamId);
}
}
/**
* Called by user
* to add SoundMeter to a stream (remote stream)
* to measure audio level. This sound Meters are added to a map with the key of StreamId.
* When user called @getSoundLevelList, the instant levels are provided.
*
* This list can be used to add a sign to talking participant
* in conference room. And also to determine the dominant audio to focus that player.
* @param {MediaStream} stream
* @param {string} streamId
*/
enableAudioLevel(stream, streamId) {
const soundMeter = new SoundMeter(this.mediaManager.audioContext);
// Put variables in global scope to make them available to the
// browser console.
// this function fetches getSoundLevelList and this list get instant levels from soundmeter directly
// so we don't need to fill inside of levelCallback here, just pass an empty function
soundMeter.connectToSource(stream, () => {}, function (e) {
if (e) {
alert(e);
return;
}
Logger.debug("Added sound meter for stream: " + streamId + " = " + soundMeter.instant.toFixed(2));
});
this.soundMeters[streamId] = soundMeter;
}
/**
* Called by the user
* to get the audio levels for the streams for the provided StreamIds
*
* @param {*} streamsList
*/
getSoundLevelList(streamsList) {
for (let i = 0; i < streamsList.length; i++) {
this.soundLevelList[streamsList[i]] = this.soundMeters[streamsList[i]].instant.toFixed(2);
}
this.notifyEventListeners("gotSoundList", this.soundLevelList);
}
/**
* Called media manaher to get video/audio sender for the local peer connection
*
* @param {string} streamId :
* @param {string} type : "video" or "audio"
* @returns
*/
getSender(streamId, type) {
var sender = null;
if (this.remotePeerConnection[streamId] != null) {
sender = this.remotePeerConnection[streamId].getSenders().find(function (s) {
return s.track.kind == type;
});
}
return sender;
}
/**
* Called by user
*
* @param {string} videoTrackId : track id associated with pinned video
* @param {string} streamId : streamId of the pinned video
* @param {boolean} enabled : true | false
* @returns
*/
assignVideoTrack(videoTrackId, streamId, enabled) {
var jsCmd = {
command: "assignVideoTrackCommand",
streamId: streamId,
videoTrackId: videoTrackId,
enabled: enabled,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called by user
* video tracks may be less than the participants count
* so these parameters are used for assigning video tracks to participants.
* This message is used to make pagination in conference.
* @param {string} streamId
* @param {number} offset : start index for participant list to play
* @param {number} size : number of the participants to play
* @returns
*/
updateVideoTrackAssignments(streamId, offset, size) {
var jsCmd = {
streamId: streamId,
command: "updateVideoTrackAssignmentsCommand",
offset: offset,
size: size,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called by user
* This message is used to set max video track count in a conference.
* @param {string} streamId
* @param {number} maxTrackCount : maximum video track count
* @returns
*/
setMaxVideoTrackCount(streamId, maxTrackCount) {
var jsCmd = {
streamId: streamId,
command: "setMaxVideoTrackCountCommand",
maxTrackCount: maxTrackCount,
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Called by user
* This message is used to send audio level in a conference.
*
* IMPORTANT: AMS v2.7+ can get the audio level from the RTP header and sends audio level to the viewers the same way here.
* Just one difference, AMS sends the audio level in the range of 0 and 127. 0 is max, 127 is ms
* It means that likely you don't need to send UPDATE_AUDIO_LEVEL anymore
*
* @param {string} streamId
* @param {*} value : audio level
* @returns
*/
updateAudioLevel(streamId, value) {
var jsCmd = {
streamId: streamId,
eventType: "UPDATE_AUDIO_LEVEL",
audioLevel: value,
};
this.sendData(streamId, JSON.stringify(jsCmd));
}
/**
* Called by user
* This message is used to get debug data from server for debugging purposes in conference.
* @param {string} streamId
* @returns
*/
getDebugInfo(streamId) {
var jsCmd = {
streamId: streamId,
command: "getDebugInfo",
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Register user push notification token to Ant Media Server according to subscriberId and authToken
* @param {string} subscriberId: subscriber id it can be anything that defines the user
* @param {string} authToken: JWT token with the issuer field is the subscriberId and secret is the application's subscriberAuthenticationKey,
* It's used to authenticate the user - token should be obtained from Ant Media Server Push Notification REST Service
* or can be generated with JWT by using the secret and issuer fields
*
* @param {string} pushNotificationToken: Push Notification Token that is obtained from the Firebase or APN
* @param {string} tokenType: It can be "fcm" or "apn" for Firebase Cloud Messaging or Apple Push Notification
*
* @returns Server responds this message with a result.
* Result message is something like
* {
* "command":"notification",
* "success":true or false
* "definition":"If success is false, it gives the error message",
* "information":"If succeess is false, it gives more information to debug if available"
*
* }
*
*/
registerPushNotificationToken(subscriberId, authToken, pushNotificationToken, tokenType) {
let jsCmd = {
command: "registerPushNotificationToken",
subscriberId: subscriberId,
token: authToken,
pnsRegistrationToken: pushNotificationToken,
pnsType: tokenType
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Send push notification to subscribers
* @param {string} subscriberId: subscriber id it can be anything(email, username, id) that defines the user in your applicaiton
* @param {string} authToken: JWT token with the issuer field is the subscriberId and secret is the application's subscriberAuthenticationKey,
* It's used to authenticate the user - token should be obtained from Ant Media Server Push Notification REST Service
* or can be generated with JWT by using the secret and issuer fields
* @param {string} pushNotificationContent: JSON Format - Push Notification Content. If it's not JSON, it will not parsed
* @param {Array} subscriberIdsToNotify: Array of subscriber ids to notify
*
* @returns Server responds this message with a result.
* Result message is something like
* {
* "command":"notification",
* "success":true or false
* "definition":"If success is false, it gives the error message",
* "information":"If succeess is false, it gives more information to debug if available"
*
* }
*/
sendPushNotification(subscriberId, authToken, pushNotificationContent, subscriberIdsToNotify) {
//type check for pushNotificationContent if json
if (typeof pushNotificationContent !== "object") {
Logger.error("Push Notification Content is not JSON format");
throw new Error("Push Notification Content is not JSON format");
}
//type check if subscriberIdsToNotify is array
if (!Array.isArray(subscriberIdsToNotify)) {
Logger.error("subscriberIdsToNotify is not an array. Please put the subscriber ids to notify in an array such as [user1], [user1, user2]");
throw new Error("subscriberIdsToNotify is not an array. Please put the subscriber ids to notify in an array such as [user1], [user1, user2]");
}
let jsCmd = {
command: "sendPushNotification",
subscriberId: subscriberId,
token: authToken,
pushNotificationContent: pushNotificationContent,
subscriberIdsToNotify: subscriberIdsToNotify
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* Send push notification to topic
* @param {string} subscriberId: subscriber id it can be anything(email, username, id) that defines the user in your applicaiton
* @param {string} authToken: JWT token with the issuer field is the subscriberId and secret is the application's subscriberAuthenticationKey,
* It's used to authenticate the user - token should be obtained from Ant Media Server Push Notification REST Service
* or can be generated with JWT by using the secret and issuer fields
* @param {string} pushNotificationContent:JSON Format - Push Notification Content. If it's not JSON, it will not parsed
* @param {string} topic: Topic to send push notification
*
* @returns Server responds this message with a result.
* Result message is something like
* {
* "command":"notification",
* "success":true or false
* "definition":"If success is false, it gives the error message",
* "information":"If succeess is false, it gives more information to debug if available"
* }
*
*/
sendPushNotificationToTopic(subscriberId, authToken, pushNotificationContent, topic) {
//type check for pushNotificationContent if json
if (typeof pushNotificationContent !== "object") {
Logger.error("Push Notification Content is not JSON format");
throw new Error("Push Notification Content is not JSON format");
}
let jsCmd = {
command: "sendPushNotification",
subscriberId: subscriberId,
token: authToken,
pushNotificationContent: pushNotificationContent,
topic: topic
};
this.webSocketAdaptor.send(JSON.stringify(jsCmd));
}
/**
* The following messages are forwarded to MediaManager. They are also kept here because of backward compatibility.
* You can find the details about them in media_manager.js
* @param {string} streamId
* @returns
*/
turnOffLocalCamera(streamId) {
return this.mediaManager.turnOffLocalCamera(streamId);
}
/**
*
* @param {string} streamId
* @returns
*/
turnOnLocalCamera(streamId) {
return this.mediaManager.turnOnLocalCamera(streamId);
}
muteLocalMic() {
this.mediaManager.muteLocalMic();
}
unmuteLocalMic() {
this.mediaManager.unmuteLocalMic();
}
/**
*
* @param {string} streamId
* @returns
*/
switchDesktopCapture(streamId) {
return this.mediaManager.switchDesktopCapture(streamId);
}
/**
* Switch to Video camera capture again. Updates the video track on the fly as well.
* @param {string} streamId
* @param {string} deviceId
* @returns {Promise}
*/
switchVideoCameraCapture(streamId, deviceId,onEndedCallback) {
return this.mediaManager.switchVideoCameraCapture(streamId,deviceId,onEndedCallback);
}
/**
* Update video track of the stream. Updates the video track on the fly as well.
* @param {string} stream
* @param {string} streamId
* @param {function} onEndedCallback
* @param {boolean} stopDesktop
* @returns {Promise}
*/
updateVideoTrack(stream, streamId, onEndedCallback, stopDesktop) {
return this.mediaManager.updateVideoTrack(stream, streamId, onEndedCallback, stopDesktop);
}
/**
* Update audio track of the stream. Updates the audio track on the fly as well. It just replaces the audio track with the first one in the stream
* @param {*} stream
* @param {*} streamId
* @param {*} onEndedCallback
* @returns
*/
updateAudioTrack(stream, streamId, onEndedCallback) {
return this.mediaManager.updateAudioTrack(stream, streamId, onEndedCallback);
}
/**
* Called by User
* to switch between front and back camera on mobile devices
*
* @param {string} streamId Id of the stream to be changed.
* @param {string} facingMode it can be ""user" or "environment"
*
* This method is used to switch front and back camera.
*/
switchVideoCameraFacingMode(streamId, facingMode) {
return this.mediaManager.switchVideoCameraFacingMode(streamId, facingMode);
}
/**
*
* @param {string} streamId
* @returns
*/
switchDesktopCaptureWithCamera(streamId) {
return this.mediaManager.switchDesktopCaptureWithCamera(streamId);
}
/**
*
* @param {string} streamId
* @param {string} deviceId
* @returns
*/
switchAudioInputSource(streamId, deviceId) {
return this.mediaManager.switchAudioInputSource(streamId, deviceId);
}
/**
*
* @param {number} volumeLevel
*/
setVolumeLevel(volumeLevel) {
this.mediaManager.setVolumeLevel(volumeLevel);
}
/**
*
* Using sound meter in order to get audio level may cause audio distortion in Windows browsers
* @param {Function} levelCallback
* @param {number} period
* @returns
*/
enableAudioLevelForLocalStream(levelCallback, period) {
return this.mediaManager.enableAudioLevelForLocalStream(levelCallback);
}
disableAudioLevelForLocalStream() {
this.mediaManager.disableAudioLevelForLocalStream();
}
/**
*
* @param {object} constraints
* @returns
*/
applyConstraints(constraints) {
return this.mediaManager.applyConstraints(constraints)
};
/**
*
* @param {number} bandwidth
* @param {string} streamId
*/
changeBandwidth(bandwidth, streamId) {
this.mediaManager.changeBandwidth(bandwidth, streamId);
}
enableAudioLevelWhenMuted() {
return this.mediaManager.enableAudioLevelWhenMuted();
}
disableAudioLevelWhenMuted() {
this.mediaManager.disableAudioLevelWhenMuted();
}
/**
*
* @param {string} streamId
* @returns
*/
getVideoSender(streamId) {
return this.mediaManager.getVideoSender(streamId);
}
/**
*
* @param {MediaStreamConstraints} mediaConstraints : media constraints to be used for opening the stream
* @param {string} streamId : id of the stream to replace tracks with
* @returns
*/
openStream(mediaConstraints, streamId) {
return this.mediaManager.openStream(mediaConstraints, streamId);
}
closeStream() {
return this.mediaManager.closeStream();
};
}
/* The Information Callbacks Called by This Class */
//TODO:
/* The Error Callbacks Called by This Class */
//TODO:
|